from flask import Flask, jsonify
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_jwt_extended import JWTManager
import os
from dotenv import load_dotenv

load_dotenv()

db = SQLAlchemy()
migrate = Migrate()
jwt = JWTManager()

def create_app():
    app = Flask(__name__)
    
    # 配置数据库
    app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('SQLALCHEMY_DATABASE_URI')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
    app.config['JWT_SECRET_KEY'] = os.getenv('SECRET_KEY')
    
    # 设置 JWT 过期时间为 30 天
    app.config['JWT_ACCESS_TOKEN_EXPIRES'] = 30 * 24 * 60 * 60  # 30天，以秒为单位
    
    # 配置CORS，允许跨域
    CORS(app, resources={r"/api/*": {"origins": "*"}})
    
    # JWT配置
    @jwt.unauthorized_loader
    def unauthorized_response(callback):
        return jsonify({
            'code': 401,
            'msg': '未登录或登录已过期'
        }), 401

    # 初始化扩展
    db.init_app(app)
    migrate.init_app(app, db)
    jwt.init_app(app)

    # 注册蓝图
    from .api import user_bp, appointment_bp, vaccine_bp, vaccination_site_bp
    app.register_blueprint(user_bp, url_prefix='/api/user')
    app.register_blueprint(appointment_bp, url_prefix='/api/appointment')
    app.register_blueprint(vaccine_bp, url_prefix='/api/vaccine')
    app.register_blueprint(vaccination_site_bp, url_prefix='/api/vaccination-site')

    return app 